<template>
  <div v-if="isSuper === 0" style="text-align: center; margin-top: 50px;">
    您的权限不够,请联系管理员升级权限。hzshenpeng@corp.netease.com
  </div>
  <div v-else>
    <!-- 搜索栏 -->
    <el-card id="search">
      <el-row type="flex" justify="space-between">
        <el-col :span="24">

          <el-input v-model="searchModel.key" placeholder="请输入搜索内容" clearable />

          <el-select v-model="searchModel.course_id" :key="searchModel.course_id" filterable placeholder="科目名称" clearable>
            <el-option v-for=" item  in  course_list " :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>

          <el-select v-model="searchModel.question_type" :key="searchModel.question_type" filterable placeholder="题目类型"
            clearable>
            <el-option v-for=" item  in  question_type_list " :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>

          <el-button type="primary" @click="getQuestionList" round icon="el-icon-search">查询</el-button>
          <el-button type="info" round icon="el-icon-download" @click="onDown">下载题库</el-button>
        </el-col>
        <template v-if="isSuper === 1">

          <el-col :span="2" class="upload-col">
            <el-button @click="openUploadDialog" type="primary">批量导入</el-button>
            <el-dialog :visible.sync="uploadDialogVisible" title="题库导入" width="30%" @close="resetUploadDialog">
              <div class="centered-content">
                <!-- 添加横线分割 -->
                <!-- <el-divider></el-divider> -->
                <!-- 导入模板链接 -->
                <div style="margin-bottom: 10px;">
                  添加文件<a href="#" @click="onExcelDown" style="color: blue;">（导入模板下载）：</a>
                </div>

                <!-- el-upload框 -->
                <el-upload class="upload-demo" ref="upload" action="#" :accept="accept" :on-preview="handlePreview"
                  :on-remove="handleRemove" :file-list="fileList" :on-change="beforeUpload" :auto-upload="false" drag
                  multiple style="width: 100%;">
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <div class="el-upload__tip" slot="tip">只能上传.xlsx文件，且不超过2MB</div>
                  <!-- 上传提示 -->
                  <div class="el-upload__tip" slot="tip" v-if="showTip">
                    请上传
                    <template v-if="fileSize">大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
                    <template v-if="fileType">格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
                    的文件
                  </div>
                </el-upload>
                <!-- 添加横线分割 -->
                <!-- <el-divider></el-divider> -->

                <!-- 批量上传按钮 -->
                <div class="centered-buttons">
                  <el-button style="margin-left: 10px;" :disabled="fileList.length < 1" size="small" type="success"
                    @click="submitUpload">
                    批量导入
                  </el-button>
                </div>
              </div>
            </el-dialog>
          </el-col>

          <el-col :span="1">

          </el-col>
          <el-col :span="1" align="right">
            <el-button @click="editQuestion(null)" type="primary" icon="el-icon-plus" circle></el-button>
          </el-col>
        </template>
      </el-row>
    </el-card>

    <!-- 查询结果栏 -->
    <el-card>
      <el-table :data="Question_list" border style="width: 100%">
        <el-table-column label="#" width="100" align="center">
          <template slot-scope="scope">
            {{
              (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" width="100" align="center">
        </el-table-column>
        <el-table-column prop="course_name" label="科目" width="100" align="center">
        </el-table-column>
        <el-table-column prop="content" label="题目" align="center">
        </el-table-column>
        <el-table-column prop="questionType" label="题目类型" width="200" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.questionType == `xz`" type="success">单选</el-tag>
            <el-tag v-else-if="scope.row.questionType == `mxz`" type="warning">多选</el-tag>
            <el-tag v-else-if="scope.row.questionType == `pd`" type="info">判断</el-tag>
            <el-tag v-else-if="scope.row.questionType == `tk`" type="primary">填空</el-tag>
            <el-tag v-else-if="scope.row.questionType == `jd`" type="danger">简答</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="isSuper === 1" label="编辑" width="200" align="center">
          <template slot-scope="scope">
            <el-button @click="editQuestion(scope.row.id)" type="primary" icon="el-icon-edit" circle
              size="mini"></el-button>
            <el-button @click="open(scope.row)" type="danger" icon="el-icon-delete" circle size="mini"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo" :page-sizes="[5, 10, 50, 100]" :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <!-- 弹出框 -->
    <el-dialog @close="clearForm" :title="title" :visible.sync="dialogFormVisible">
      <!-- <el-dialog :title="title" :visible.sync="dialogFormVisible"> -->
      <el-form :model="QuestionForm" ref="questionForm" :rules="formRules">
        <!-- <el-form-item label="科目名称：" prop="Question_name" v-if="QuestionForm.id == null || QuestionForm.id == undefined"
          :label-width="formLabelWidth">
          <el-input v-model="QuestionForm.Question_name" autocomplete="off"></el-input>
        </el-form-item> -->
        <el-form-item label="科目名称:" prop="course_id" :label-width="formLabelWidth">
          <el-select v-model="QuestionForm.course_id" :key="QuestionForm.course_id" filterable placeholder="科目名称"
            clearable>
            <el-option v-for=" item  in  course_list " :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题目类型：" prop="questionType" :label-width="formLabelWidth">
          <el-select v-model="QuestionForm.questionType" placeholder="题目类型" clearable>
            <el-option v-for=" item  in  question_type_list " :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分值：" prop="score" :label-width="formLabelWidth">
          <el-select v-model="QuestionForm.score" placeholder="题目类型" clearable>
            <el-option v-for=" item  in  score_list " :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本:" prop="release" :label-width="formLabelWidth">
          <el-input v-model="QuestionForm.release" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="章节:" prop="chapter" :label-width="formLabelWidth">
          <el-input v-model="QuestionForm.chapter" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="题目:" prop="content" :label-width="formLabelWidth">
          <el-input v-model="QuestionForm.content" autocomplete="off" class="custom-width"></el-input>
        </el-form-item>

        <template v-if="QuestionForm.questionType == `xz`">
          <el-form-item label="答案:" prop="answer" :label-width="formLabelWidth">
            <el-radio-group v-model="QuestionForm.answer" size="medium">
              <el-radio-button v-for="xz in xzs" :label="xz" :key="xz">{{ xz }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选项A:" prop="choice_a" :label-width="formLabelWidth">
            <textarea v-model="QuestionForm.choice_a" autocomplete="off" rows="10" class="custom-width"></textarea>
          </el-form-item>
          <el-form-item label="选项B:" prop="choice_b" :label-width="formLabelWidth">
            <textarea v-model="QuestionForm.choice_b" autocomplete="off" rows="10" cols="83"
              class="custom-width"></textarea>
          </el-form-item>
          <el-form-item label="选项C:" prop="choice_c" :label-width="formLabelWidth">
            <textarea v-model="QuestionForm.choice_c" autocomplete="off" rows="10" cols="83"
              class="custom-width"></textarea>
          </el-form-item>
          <el-form-item label="选项D:" prop="choice_d" :label-width="formLabelWidth">
            <textarea v-model="QuestionForm.choice_d" autocomplete="off" rows="10" cols="83"
              class="custom-width"></textarea>
          </el-form-item>
        </template>
        <template v-else-if="QuestionForm.questionType === `mxz`">
          <el-form-item label="答案:" prop="answer" :label-width="formLabelWidth">
            <el-checkbox-group v-model="selectedOptions" size="medium">
              <el-checkbox-button v-for="xz in xzs" :label="xz" :key="xz">{{ xz }}</el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="选项A:" prop="choice_a" :label-width="formLabelWidth">
            <textarea v-model="QuestionForm.choice_a" autocomplete="off" rows="10" class="custom-width"></textarea>
          </el-form-item>
          <el-form-item label="选项B:" prop="choice_b" :label-width="formLabelWidth">
            <textarea v-model="QuestionForm.choice_b" autocomplete="off" rows="10" cols="83"
              class="custom-width"></textarea>
          </el-form-item>
          <el-form-item label="选项C:" prop="choice_c" :label-width="formLabelWidth">
            <textarea v-model="QuestionForm.choice_c" autocomplete="off" rows="10" cols="83"
              class="custom-width"></textarea>
          </el-form-item>
          <el-form-item label="选项D:" prop="choice_d" :label-width="formLabelWidth">
            <textarea v-model="QuestionForm.choice_d" autocomplete="off" rows="10" cols="83"
              class="custom-width"></textarea>
          </el-form-item>
        </template>
        <template v-else-if="QuestionForm.questionType == `tk` || QuestionForm.questionType === `jd`">
          <el-form-item label="答案:" prop="answer" :label-width="formLabelWidth">
            <textarea v-model="QuestionForm.answer" autocomplete="off" rows="15" class="custom-width"></textarea>
          </el-form-item>
        </template>
        <template v-else-if="QuestionForm.questionType == `pd`">
          <el-form-item label="答案:" prop="answer" :label-width="formLabelWidth">
            <el-radio-group v-model="QuestionForm.answer" size="medium">
              <el-radio-button v-for="pd in pds" :label="pd" :key="pd">{{ pd }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </template>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button @click="addQuestion" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import testApi from "@/api/testMange";
import { mapGetters } from 'vuex';

const xzOptions = ['A', 'B', 'C', 'D'];

const pdOptions = ['对', '错'];
export default {
  // name: "Image",
  props: {
    // 值
    value: [String, Object, Array],
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 2,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']数组
    fileType: {
      type: Array,
      // default: () => [".jpg", ".jpeg", ".png", ".doc", ".xls", ".xlsx", ".ppt", ".txt", ".pdf"],
      default: () => [".xlsx"],
    },
  },
  data() {
    return {
      // 其他数据...
      formRules: {
        course_id: [
          { required: true, message: '请输入科目名称', trigger: 'blur' },
        ],
        questionType: [
          { required: true, message: '请输入题目类型', trigger: 'blur' },
          // 其他校验规则
        ],
        score: [
          { required: true, message: '请输入分值', trigger: 'blur' },
          // 其他校验规则
        ],
        release: [
          { required: true, message: '请输入版本', trigger: 'blur' },
          // 其他校验规则
        ],
        chapter: [
          { required: true, message: '请输入章节', trigger: 'blur' },
          // 其他校验规则
        ],
        answer: [
          { required: true, message: '请输入答案', trigger: 'blur' },
          // 其他校验规则
        ],
        content: [
          { required: true, message: '请输入题目内容', trigger: 'blur' },
          // 其他校验规则
        ],
        // 其他字段的校验规则
      },
      xzs: xzOptions,
      pds: pdOptions,
      fileList: [],//上传的文件列表
      accept: '',//可上传的文件类型
      showTip: false,
      uploadDialogVisible: false,
      QuestionForm: {
        // "idc_name": "",
        // "is_active": 0,
        "answer": "",
        "choice_a": "A.",
        "choice_b": "B.",
        "choice_c": "C.",
        "choice_d": "D.",
      },
      formLabelWidth: "130px",
      dialogFormVisible: false,
      title: "",
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 10,
      },
      userList: [],
      course_list: [],
      Question_list: [],
      question_type_list: [
        {
          value: 'xz',
          label: '单选'
        }, {
          value: 'mxz',
          label: '多选'
        }, {
          value: 'tk',
          label: '填空'
        }, {
          value: 'jd',
          label: '简答'
        }, {
          value: 'pd',
          label: '判断'
        }
      ],
      score_list: [
        { value: 5, label: '5分' },
        { value: 20, label: '20分' },
      ],
    };
  },
  methods: {
    openUploadDialog() {
      this.uploadDialogVisible = true;
    },
    resetUploadDialog() {
      this.uploadDialogVisible = false;
      // 您可以在这里重置其他与上传相关的数据
    },
    // 上传文件之前的钩子：判断上传文件格式、大小等，若返回false则停止上传
    beforeUpload(file, fileList) {
      //文件状态改变时的钩子，文件变化时给fileList赋值，fileList通过这种方式获取值；
      this.fileList = fileList;
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";//file的后缀名
        //file name test.pdf
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf("."));//获取file后缀名
        }
        //循环遍历fileType数组，传入的文件后缀名是否在数组中
        const isTypeOk = this.fileType.some((type) => {
          // if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用；和handleChange函数绑定，文件变化时给fileList赋值，fileList通过这种方式获取值；
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    submitUpload() { //上传到服务器
      const param = new FormData();//发送的数据应为FormDate格式，因此新建一个FormDate格式的param变量存放上传的文件列表；
      this.fileList.forEach(//不能直接将fileList数组赋给param变量，应该对fileList进行forEach遍历，通过val.raw来取得文件内容赋给param变量
        val => {
          //把多个文件放到同一个请求里，这样只会请求一次接口。否则一个文件就会请求一次
          param.append("file", val.raw);
        }
      );

      testApi.mutliUpload(param).then((reponse) => {
        this.fileList = [],
          // 提示提交成功
          this.$message({
            message: reponse.message,
            type: "success",
          });
        //关闭弹窗
        this.uploadDialogVisible = false;
        // 刷新页面
        this.getQuestionList();
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },

    // downloadTemplate 方法
    // downloadTemplate() {
    //   // 使用 axios 或其他请求库调用后端接口
    //   testApi.downloadTemplate().then(res => {
    //                 let blobUrl = window.URL.createObjectURL(new Blob([res.data], {
    //                     type: "application/vnd.ms-excel",
    //                 }))
    //                 const a = document.createElement("a");
    //                 a.style.display = "none";
    //                 a.download = "投放组合评估.xlsx";
    //                 a.href = blobUrl;
    //                 a.click();
    //             });
    // },

    // 下载模板
    async downloadTemplateData() {
      try {
        // 使用 axios 或其他请求库调用后端接口
        const response = await testApi.downloadTemplate()
        // console.log(response)
        // const jsonData = JSON.parse(response.data) // 将 JSON 字符串转换为对象
        return response
      } catch (error) {
        console.error('下载模板数据失败', error)
        throw new Error('下载模板数据失败')
      }
    },

    async onExcelDown() {
      this.$message({ type: 'warning', message: '数据读取中，请稍后' })
      this.loading = true

      try {
        // 获取后端接口数据，这里使用 axios 发送请求
        const response = await this.downloadTemplateData()
        const jsonData = response.data
        // console.log(jsonData)

        this.loading = false
        const filename = 'idcsExamTemplate'
        const autoWidth = true
        const bookType = 'xlsx'
        const header = ['科目', '试题类型', '分值', '版本', '章节', '题目', '答案', '选项A', '选项B', '选项C', '选项D']
        const headValue = ['course_name', 'question_type', 'score', 'release', 'chapter', 'content', 'answer', 'choice_a', 'choice_b', 'choice_c', 'choice_d']

        const formatJson = (headValue, jsonData) => {
          // console.log('jsonData type:', typeof jsonData); // 添加这行用于调试
          return jsonData.map((v) => headValue.map((j) => v[j]))
        }


        import('/vendor/Export2Excel.js').then(module => {
          module.export_json_to_excel({
            header,
            data: formatJson(headValue, jsonData),
            filename,
            autoWidth,
            bookType
          })
        })

      } catch (error) {
        console.error('获取数据失败', error)
        this.$message({ type: 'error', message: '获取数据失败，请重试' })
        this.loading = false
      }
    },

    // 下载题库

    async downloadData() {
      try {
        // 使用 axios 或其他请求库调用后端接口
        const response = await testApi.download(this.searchModel)
        // console.log(response)
        // const jsonData = JSON.parse(response.data) // 将 JSON 字符串转换为对象
        return response
      } catch (error) {
        console.error('下载模板数据失败', error)
        throw new Error('下载模板数据失败')
      }
    },

    async onDown() {
      this.$message({ type: 'warning', message: '数据读取中，请稍后' })
      this.loading = true

      try {
        // 获取后端接口数据，这里使用 axios 发送请求
        const response = await this.downloadData()
        const jsonData = response.data
        // console.log(jsonData)

        this.loading = false
        const filename = '题库'
        const autoWidth = true
        const bookType = 'xlsx'
        const header = ['ID', '科目', '试题类型', '分值', '版本', '章节', '题目', '答案', '选项A', '选项B', '选项C', '选项D']
        const headValue = ['id', 'course_name', 'question_type', 'score', 'release', 'chapter', 'content', 'answer', 'choice_a', 'choice_b', 'choice_c', 'choice_d']

        const formatJson = (headValue, jsonData) => {
          // console.log('jsonData type:', typeof jsonData); // 添加这行用于调试
          return jsonData.map((v) => headValue.map((j) => v[j]))
        }


        import('/vendor/Export2Excel.js').then(module => {
          module.export_json_to_excel({
            header,
            data: formatJson(headValue, jsonData),
            filename,
            autoWidth,
            bookType
          })
        })

      } catch (error) {
        console.error('获取数据失败', error)
        this.$message({ type: 'error', message: '获取数据失败，请重试' })
        this.loading = false
      }
    },

    open(Question) {
      this.$confirm(`您是否确认删除ID为${Question.id}的试题?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          testApi.deleteQuestionById(Question.id).then((response) => {
            this.$message({
              type: "success",
              message: response.message,
            });
            this.getQuestionList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    addQuestion() {
      // 表单验证
      this.$refs.questionForm.validate((valid) => {
        if (valid) {
          testApi.saveQuestion(this.QuestionForm).then((reponse) => {
            // 关闭弹窗
            this.dialogFormVisible = false;
            // 提示提交成功
            this.$message({
              message: reponse.message,
              type: "success",
            });
            // 刷新页面
            this.getQuestionList();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    clearForm() {
      this.QuestionForm = {
        // "idc_name": "",
        // "is_active": 0,
        "answer": "",
        "choice_a": "A.",
        "choice_b": "B.",
        "choice_c": "C.",
        "choice_d": "D.",
      };
      this.$refs.questionForm.clearValidate();
    },
    editQuestion(id) {
      if (id == null) {
        this.title = "新增试题";
      } else {
        this.title = "修改试题";
        //先从后端获取user信息
        testApi.getQuestionById(id).then((reponse) => {
          this.QuestionForm = reponse.data;
        });
      }
      this.dialogFormVisible = true;
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.getQuestionList();
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo;
      this.getQuestionList();
    },
    getQuestionList() {
      testApi.getQuestionList(this.searchModel).then((response) => {
        this.total = response.data.total;
        this.Question_list = response.data.api_question_list;
        this.course_list = response.data.api_course_list;
      });
    },
  },
  created() {
    this.getQuestionList();
    // 从数据中拼接fileType可以接收的类型
    this.fileType.forEach(el => {
      this.accept += el
      this.accept += ','
    })
    this.fileType.slice(0, this.fileList.length - 2)
  },
  computed: {
    ...mapGetters([
      // 'name',
      'isSuper',
      // 'nick_name'
    ]),
    selectedOptions: {
      get() {
        // 将字符串转换为数组
        return this.QuestionForm.answer ? this.QuestionForm.answer.split('') : [];
      },
      set(value) {
        // 将数组转换为字符串
        this.QuestionForm.answer = value.sort().join('');
      }
    }
  }
};
</script>

<style>
#search .el-input {
  width: 200px;
  margin-right: 10px;
}

.el-dialog .el-input {
  width: 88%;
}

.upload-col {
  display: flex;
  align-items: center;
}

.custom-width {
  width: 88%;
  /* 或者其他你想要的宽度值 */
}

.centered-buttons {
  text-align: center;
  margin-top: 10px;
  /* Adjust as needed */
}

.el-upload {
  width: 100%;
}

.el-upload__input {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
}

.el-upload-dragger i {
  font-size: 32px;
  color: #8c939d;
  margin-bottom: 10px;
}

.el-upload-dragger p {
  font-size: 14px;
  color: #8c939d;
  margin: 0;
}

/* .centered-content {
  display: flex;
  flex-direction: column;
  align-items: center;
} */
</style>